﻿/**
* Author: Zero
* Version 1.8
* Clase que se encarga de relacionar el CENTRAL.SWF con el resto de la aplicación
* A ella le corresponde disparar los eventos a las extensions, etc
* Le saqué la problemática de los filtros, hay que revisar cómo se resuelve eso
* se agrega un getMessages que pide el EXTENSIONBridge.as
* conoce a WindowCabeza, y le pide a ExtensionsToClips que labure dentro de esa ventana
* se agrega el hecho de poseer una Active Extension
* inicializa el stage y el system
* se encarga de cargar un SWF que contiene un CONSOLEBridge dentro
* + tenemos que resolver el tema de si los contactos llevan extensiones adentro, para la demo lo dejamos que el phonenumber es igual al extId
* + revisar el logOut() es bastante cabezón
* 
*/

import com.dinmax.flash.central.*
import com.dinmax.flash.central.draw.*
import com.dinmax.flash.central.bridge.*
import com.dinmax.flash.central.extension.*
import com.dinmax.flash.central.extension.user.Contact
import com.dinmax.flash.central.extension.state.*
import com.dinmax.flash.central.extension.message.*

import com.dinmax.flash.draw.common.Point

import com.dinmax.flash.draw.cabeza.WindowCabeza
import com.dinmax.flash.draw.cabeza.WindowCabezaLayout

class CENTRALBridge {
			
	private static var PATH_CONSOLE:String="botoneraCentral.swf";
	private static var LEVEL_CONSOLE:Number=100;
	private static var bridge:CENTRALBridge;
	
	private var loopIntro:MovieClip;
	
	private var windowCentral:WindowCabeza;
	private var console:CONSOLEBridge;
	private var loader:MovieClipLoader;
	private var loaderListener:Object;
				
	public static function newInstance(windowCentral:WindowCabeza):Void {
		bridge= new CENTRALBridge(windowCentral);
	}; //fin funci	
	
	public static function getActive():CENTRALBridge {
		return bridge;
	}; //fin funci
	
	function CENTRALBridge(windowCentral:WindowCabeza){
		windowCentral.setLayout(new WindowCabezaLayout(windowCentral));
		this.loopIntro = _root.loopIntro;
		this.windowCentral=windowCentral;
		this.initConsole();
		this.init();
		return;
	};

	private function init():Void {
		//seteo cosas de la pantalla y del sistema
		Stage.showMenu =false;
		Stage.scaleMode = "noScale";
		System.useCodepage = true;
		//
				
		CENTRAL.newInstance(this);
		DepthManager.newInstance();
		return;
	};
	private function initConsole():Void {
		var root:CENTRALBridge = this;
		// creo el object que va a escuchar al MovieClipLoader y le defino el evento onLoadInit
		loaderListener = new Object();
		loaderListener.onLoadInit= function(target:MovieClip):Void {
			//root.setConsole(target);
			//root.getConsole().setBridge(root);
		};
		// creo el movieClipLoader y le agrego como listener al loaderList
		loader = new MovieClipLoader();
		loader.addListener(loaderListener);
		// cargo la botonera y le asigno el nivel
		loader.loadClip(CENTRALBridge.PATH_CONSOLE, CENTRALBridge.LEVEL_CONSOLE);
		return;
	};
	public function setConsole(console:CONSOLEBridge):Void {
		this.console = console;
		return;
	};
	public function getConsole():CONSOLEBridge {
		return this.console;
	};
	public function createRootExtension():EXTENSIONBridge {
		return this.console.createRootExtension();
	};
	
	// SWF 2 THIS
	public function logIn(user:String, password:String):Void {
		//trace("CENTRALBridge.as | logIn() user= "+user+" pass= "+password); 
		CENTRAL.getActive().logIn(user, password);
		return;
	};
	
	public function logOut():Void {
		//esto es re cabeza
		this.loopIntro._alpha= 100;
		this.loopIntro.gotoAndPlay(1);
		//
		CENTRAL.getActive().logOut();
		windowCentral.deleteItems();
		ExtensionsToClips.newInstance();
		init();
		initConsole();
		return;
	};
	
	
	//CENTRAL 2 BRIDGE

	public function CENTRAL_2_BRIDGE_setExtensions(extensions:Extensions, activeExtensionID:Number):Void{
		this.loopIntro.gotoAndStop("end");
		if(ExtensionsToClips.getActive() == undefined) ExtensionsToClips.newInstance();
		ExtensionsToClips.getActive().setExtensions(extensions, activeExtensionID, windowCentral, this);
		return;
	};
		
	public function getExtensions():Extensions {
		return ExtensionsToClips.getActive().getExtensions();
	};
	
	public function getExtension(clip:MovieClip):Extension {
		return ExtensionsToClips.getActive().getExtension(clip);
	};
	
	public function getExtensionId(ext:MovieClip):Number {
		return getExtension(ext).getId();
	};
	
	public function isExtensionAutorized(ext:MovieClip):Boolean {
		return ExtensionsToClips.getActive().isExtensionAutorized(ext);
	};
	public function isRootExtension(ext:MovieClip):Boolean {
		return ExtensionsToClips.getActive().isExtensionAutorized(ext);
	};
		
	//


	//EXTENSIONBridge 2 THIS
	
	public function EXTENSIONBridge_2_CENTRALBridge_getState(clip:MovieClip):Void{
		//trace("CENTRALBridge.as | EXTENSIONBridge_2_CENTRALBridge_getState() extension: "+clip);
		var xt:Extension = getExtension(clip);
		//trace("CENTRALBridge.as | 123 | callerId 177= "+this.callerId(177, xt));
		if(xt.getState().isDisabled()){
			clip.setDisabled(xt.getUser().getNick());

		} else if (xt.getState().isEnabled()){
						
			if(xt.getState().isCalling()){
				clip.setCalling(String(Calling(xt.getState()).getExtension().getNumber()));
			} else if (xt.getState().isRinging()){
				//clip.setRinging(String(Ringing(xt.getState()).getExtension().getNumber()));
				clip.setRinging(this.callerId(Ringing(xt.getState()).getExtension().getNumber(), xt));
			} else if(xt.getState().isActive()){
				clip.setTalking(String(Active(xt.getState()).getExtension().getNumber()));	
			} else {
				clip.setEnabled(xt.getUser().getNick());
			};
			
		};
		
		return;
		
	};
		
	public function getUserData(clip:EXTENSIONBridge, target:MovieClip):Void {
		var xt:Extension = getExtension(clip);
		target.setUserData(xt.getUser().getNick(), xt.getUser().getName(), xt.getUser().getLastName(), xt.getUser().getEmail());
		return;
	};
	
	public function getUserContacts(clip:MovieClip, target:MovieClip):Void {
		
		var xt:Extension = getExtension(clip);
		var a:Array = new Array();
		for (var i:Number =0; i < xt.getUser().getContacts().getItems().length; i++){
			var cnt:Contact = xt.getUser().getContacts().getItems()[i];
			target.addContact(cnt);
			
		};
		return;
	};
	public function callerId(fromId:Number, ext:Extension):String {
		var contact:Contact = ext.getUser().getContacts().getItem(fromId);
		var nick:String = contact.getNick();
		if(nick == undefined){
			nick = String(fromId);
		} else {
			//trace("CENTRALBridge.as callerId() nick= "+nick);
		};
		return nick;
	};
	
	public function getLog(clip:MovieClip, target:MovieClip):Void {
		var items:Array = this.getExtension(clip).getLog().getItems();
		var nItems:Number = items.length;
		target.resetLog();
		for (var i : Number = 0; i < nItems; i++) {
			var s:State = State(items[i]);
			target.addLog(s.getTime(), s.getName(), s.getDescription());
		}
		return;
	};
	
	public function getNewTextMessages(clip:MovieClip):Number {
		var xt:Extension = getExtension(clip);
		return (MessageUtils.getMessagesByState(xt.getTextMessages(), Message.NEW).length);
	};
	
	public function getNewVoiceMessages(clip:MovieClip):Number {
		var xt:Extension = getExtension(clip);
		return (MessageUtils.getMessagesByState(xt.getVoiceMessages(), Message.NEW).length);
	};
	
	public function getTextMessages(clip:MovieClip, target:MovieClip):Void {
		var xt:Extension = getExtension(clip);
		var msgs:Array = MessageUtils.orderMessages(xt.getTextMessages());
		var nMsg:Number = msgs.length;
		for (var i : Number = 0; i < nMsg; i++) {
			var msg:TextMessage=TextMessage(msgs[i]);
			target.addTextMessage(msg);
		};
		return;
	};
	
	public function getVoiceMessages(clip:MovieClip, target:MovieClip):Void {
		var xt:Extension = getExtension(clip);
		var msgs:Array = MessageUtils.orderMessages(xt.getVoiceMessages());
		var nMsg:Number = msgs.length;
		for (var i : Number = 0; i < nMsg; i++) {
			var msg:VoiceMessage=VoiceMessage(msgs[i]);
			target.addVoiceMessage(msg);
		};
		return;
	};
	
	public function refreshVoiceMessages(ext:EXTENSIONBridge):Void {
		CENTRAL.getActive().refreshVoiceMessages(getExtensionId(ext));
		return;
	};
	public function writeMessage(to:Number):Void {
		//trace("CentralBridge.as | writeMessage() to= "+to);
		//ExtensionsToClips.getRootClip().writeMessage(to);
		this.getConsole().getRootButtons().writeMessage(to);
	};
	
	public function sendMessage(to:Number, subject:String, body:String):Void {
		CENTRAL.getActive().sendMessage(to, subject, body);
		return;
	};
	
	public function readMessage(msg:Message, extClip:MovieClip):Void {
		CENTRAL.getActive().readMessage(msg, getExtensionId(extClip));
		return;
	};
	public function deleteMessage(msg:Message, extClip:MovieClip):Void {
		CENTRAL.getActive().deleteMessage(msg, getExtensionId(extClip));
		return;
	};
	public function outgoingCall(to:Number):Void {
		CENTRAL.getActive().outgoingCall(to);
	};
	public function saveContact(from:MovieClip, contact:Contact):Void {
		CENTRAL.getActive().saveContact(getExtension(from).getUser().getId(), contact)
	};
	public function deleteContact(contactId:Number):Void {
		CENTRAL.getActive().deleteContact(contactId);
	};
	public function addShortcut(name:String, email:String, phone:Number):Void {
		CENTRAL.getActive().addShortcut(name, email, phone);
		return;
	};	
	//
	

};